package dao;

import bean.Employee;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import java.util.List;

public class EmployeeDAOImpl implements EmployeeDAO {
    private Session session;
    private Transaction transaction;
    private boolean completed;

    public EmployeeDAOImpl(Session session) {
        this.session = session;
    }

    @Override
    public boolean add(Employee employee) {
        try {
            transaction = session.beginTransaction();
            session.save(employee);
            completed = true;
        } catch (Exception e) {
            completed = false;
            e.printStackTrace();
        } finally {
            transaction.commit();
        }
        return completed;
    }

    @Override
    public boolean edit(Employee temporary) {
        try {
            transaction = session.beginTransaction();
            Employee employee = session.get(Employee.class, temporary.getEmployeeId());
            employee.setEmployeeName(temporary.getEmployeeName());
            employee.setDepartmentId(temporary.getDepartmentId());
            employee.setPositionId(temporary.getPositionId());
            session.update(employee);
            completed = true;
        } catch (Exception e) {
            completed = false;
            e.printStackTrace();
        } finally {
            transaction.commit();
        }
        return completed;
    }

    @Override
    public boolean remove(int employeeId) {
        try {
            transaction = session.beginTransaction();
            Employee employee = session.get(Employee.class, employeeId);
            session.delete(employee);
            completed = true;
        } catch (Exception e) {
            completed = false;
            e.printStackTrace();
        } finally {
            transaction.commit();
        }
        return completed;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Employee> queryAll() {
        List<Employee> employees = null;
        try {
            Query<Employee> query = session.createQuery("FROM Employee");
            employees = query.list();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return employees;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Employee query(int employeeId) {
        Employee employee = null;
        try {
            Query<Employee> query = session.createQuery("FROM Employee WHERE employeeId=" + employeeId);
            employee = query.list().get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return employee;
    }
}
